package com.xyz.lottery;

import java.math.BigDecimal;
import java.util.List;

public class Lotteryer{

    private List<LotteryProbablity> probablities;

    private BigDecimal totalRate = BigDecimal.ZERO;

    private BigDecimal totalGoal = BigDecimal.ONE;

    private Lotteryer(List<LotteryProbablity> probalities){
        initByProbalites(probalities);
    }

    private Lotteryer(List<LotteryProbablity> probalities, BigDecimal totalGoal){
        this.totalGoal = totalGoal;
        initByProbalites(probalities);
    }

    private void initByProbalites(List<LotteryProbablity> probalities){
        if(probalities == null || probalities.size() == 0){
            throw new LotteryException("抽奖配置失败");
        }
        this.probablities = probalities;
        this.probablities.forEach(x->{
            x.setStartProbablity(totalRate);
            totalRate = totalRate.add(x.getProbablity());
            x.setEndProbablity(totalRate);
        });
        if(totalRate.compareTo(totalGoal) > 0){
            throw new LotteryException("总概率应该在1之内");
        }
    }

    public static Lotteryer instance(List<LotteryProbablity> probalities){
        return new Lotteryer(probalities);
    }

    public static Lotteryer instance(List<LotteryProbablity> probalities, BigDecimal totalGoal){
        return new Lotteryer(probalities,totalGoal);
    }

    public LotteryProbablity lottery(){
        BigDecimal randomProbality = new BigDecimal(Math.random());
        System.out.println("概率:" + randomProbality);
        return this.probablities.stream().filter(x->{
            if(x.getStartProbablity().compareTo(randomProbality) <=0 &&
            x.getEndProbablity().compareTo(randomProbality) >= 0){
                return true;
            }
            return false;
        }).findFirst().orElse(null);
    }
}
